#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
import MySQLdb
import time
import os
file = sys.argv[1]
host = sys.argv[2]
port = sys.argv[3]
user = sys.argv[4]
password = sys.argv[5]
db = sys.argv[6]
day = sys.argv[7]
tablename = sys.argv[8]

def format_float(a):
    if a:
        return round(float(a), 2)

def transformPay(ispay):
    if "True" in ispay:
        return 1
    else:
        return 0
    
def format_str(a):
    if '"' in a:
        return str(a.replace('"', ''))
    elif "'" in a:
        return str(a.replace("'", ''))
    return str(a)

def format_url(a):
    a = str(a)
    if '"' in a:
        a = str(a.replace('"', ''))
    elif "'" in a:
        a = str(a.replace("'", ''))

    if len(a) > 500:
        return a[:500]
    return a

def format_escape(a):
    if a and str(a)[-1]=='\\':
        a = a[:-1]
    return a
    
if os.path.exists(file):
    conn = MySQLdb.connect(host, user, password, db)
    cursor = conn.cursor()
    cursor.execute("SET NAMES utf8")
    columns = 'cid,sid,day,refererType,refererInfo,refererProperties,pv,uv,ip,bounce,averageAccessTime,session,conversions,ispay,se,update_time'
    columns_info = {'cid':'str', 'sid':'str', 'day':'int', 'refererType':'format_str', 'refererInfo':'format_str', 'refererProperties':'format_url', 'pv':'long', 'uv':'long', 'ip':'long', 'bounce':'long', 'averageAccessTime':'format_float', 'session':'long', 'conversions':'long', 'ispay':'transformPay', 'se':'str', 'update_time':'int'}
    c_l = columns.strip().split(',')
    args = ','.join(['%s' % i for i in c_l])
    args2 = ','.join(['%s' for i in c_l])
    lines = []
    update_time = int(time.time())
    with open(file) as f:
        for i in f:
            l = i.rstrip('\n').split('\001')
            if l[0] and l[1]:
                l.append(update_time)
                lines.append(tuple([eval("%s('''%s''')" % (columns_info[c_l[index]], format_escape(j) if j else '0')) for index, j in enumerate(l)]))
    if len(lines) > 0:
        sql = 'insert into %s(%s) values(%s)' % (tablename, args, args2)
        cursor.executemany(sql, tuple(lines))
        conn.commit()
        delete_sql = "delete from %s where day='%s' and update_time!=%s" % (tablename, day, update_time)
        cursor.execute(delete_sql)
        conn.commit()
    cursor.close()
    conn.close()
